<?php
class Warehouses_product_model extends CI_Model {

    var $id = '';
    var $id_stock = '';
    var $id_product = '';
    var $available = '';
    private $_tabla = 'warehouses_product';

    function __construct() {
        // Call the Model constructor
        parent::__construct();
    }

    public function getAll()
    {
        $this->db->select();
        $query = $this->db->get($this->_tabla);
        return $query->result();
    }
    
    public function find($id)
    {
        $query = $this->db->where('id = '.$id)->get($this->_tabla);
        $rs = $query->result();
        return $rs[0];
    }
	
	public function remove($code_product,$code_almacen,$caja_almacen,$paquete_almacen,$unidad_almacen){
		$query = $this->db->query("UPDATE warehouses_product set units=units-'$unidad_almacen',packs =packs-'$paquete_almacen',boxes=boxes-'$caja_almacen' WHERE `id_product` = '$code_product' and `id_warehouse` = '$code_almacen'"); 
	}
    
    public function add($code_product,$code_almacen,$caja_almacen,$paquete_almacen,$unidad_almacen,$tipo)
    {
        if($tipo == 0)
        {
			$query = $this->db->query("INSERT INTO warehouses_product (`id`, `id_warehouse`, `id_product`, `Units`, `packs`, `boxes`) VALUES (NULL, '$code_almacen', '$code_product', '$unidad_almacen', '$paquete_almacen', '$caja_almacen')");                                
        }
        else
        {
			$query = $this->db->query("UPDATE warehouses_product set units=units+'$unidad_almacen',packs =packs+'$paquete_almacen',boxes=boxes+'$caja_almacen' WHERE `id_product` = '$code_product' and `id_warehouse` = '$code_almacen'");
        }
   }
    
    public function listStockByProduct($product_id)
    {
        $this->db->select();
        $this->db->from($this->_tabla);
        $this->db->join('warehouses', "warehouses.id = ".$this->_tabla.".id_warehouse", 'left');        
        $this->db->where('id_product', $product_id);
        $query = $this->db->get();
        return $query->result();
    }
    
    public function listStockByProductAndWarehouse($codeProduct,$codewarehouse)
    {
        $this->db->select();
        $this->db->from($this->_tabla);               
        $this->db->where('id_product', $codeProduct);
        $this->db->where('id_warehouse', $codewarehouse);
        $query = $this->db->get();
        return $query->result();
    }

    public function delete($code)
    {
        $this->db->where('id_warehouse', $code);
        $this->db->update($this->_tabla, array('status' => 0));
        return true; 
    }

    public function update($id, $data)
    {
        $this->db->where('id', $id);
        $this->db->update($this->_tabla, $data);
        return true;
    }
}